<?php

namespace App\Http\Controllers\Backend;

use App\Http\Requests\Course\Category\CreateRequest;
use App\Http\Requests\Course\Category\UpdateRequest;
use App\Models\Category;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class CategoryController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $user = \Auth::user();
        if (!$user->hasPermissionTo('分类管理')) {
            return view('error.error');
        }
        $categorys = Category::paginate(15);
        return view('category.list', ['categorys' => $categorys]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $user = \Auth::user();
        if (!$user->hasPermissionTo('分类管理')) {
            return view('error.error');
        }
        return view('category.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param CreateRequest $request
     * @return \Illuminate\Http\Response
     * @throws \Throwable
     */
    public function store(CreateRequest $request)
    {
        $model = \DB::transaction(function () use ($request) {
            $attributes = $request->validated();
            $model = Category::create($attributes);
            return $model;
        });
        return redirect()->route('category.index')->with('success', '添加成功');
    }

    /**
     * Display the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function show()
    {

    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function edit(Category $category)
    {
        $user = \Auth::user();
        if (!$user->hasPermissionTo('分类管理')) {
            return view('error.error');
        }
        return view('category.create', ['category' => $category]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param UpdateRequest $request
     * @param Category $category
     * @return \Illuminate\Http\Response
     * @throws \Throwable
     */
    public function update(UpdateRequest $request, Category $category)
    {
        $model = \DB::transaction(function () use ($request, $category) {
            $attributes = $request->validated();
            $model = $category->update($attributes);
            return $model;
        });
        return redirect()->route('category.index')->with('success', '编辑成功');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}
